apiKey-handler.js ➔ apiKeyHandler   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 27
ccs 10
cts 10
cp 1
rs 9.1832
c 0
b 0
f 0
cc 5
crap 5
1
// eslint-disable-next-line no-unused-vars
2
import express from "express";
3
import apiKeyModel from "../models/api-key.js";
4
5
/**
6
 *
7
 * @param {express.Request} req
8
 * @param {express.Response} res
9
 * @param {express.NextFunction} next
10
 */
11
async function apiKeyHandler(req, res, next) {
12 100
    if (req.path === "/admin/feed") {
13 2
        return next();
14
    }
15
16 98
    const apiKey = req.headers['x-api-key'];
17
18 98
    const apiKeyString = Array.isArray(apiKey) ? apiKey[0] : apiKey;
19
20 98
    if (!apiKeyString) {
21 1
        return res.status(401).json({
22
            success: false,
23
            message: 'API key is required.'
24
        });
25
    }
26
27 97
    const isValidKey = await apiKeyModel.checkOne(apiKeyString);
28
29 97
    if (!isValidKey) {
30 1
        return res.status(401).json({
31
            success: false,
32
            message: 'Invalid or missing API key. Access denied.'
33
        });
34
    }
35
36 96
    return next();
37
}
38
39
export default apiKeyHandler;
40